﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mengsk.ProxyDelivery.Print.Domain.DeliveryNumberGenerator
{
    class DeliveryNumberGeneratorManager
    {
        private static List<DeliveryNumberGenerator> gens = new List<DeliveryNumberGenerator>();

        static DeliveryNumberGeneratorManager()
        {
            Type[] types = Assembly.GetExecutingAssembly().GetTypes().Where(obj => obj.BaseType != null && obj.BaseType == typeof(DeliveryNumberGenerator)).ToArray();
            DeliveryNumberGenerator[] objs = types.Select(obj => Activator.CreateInstance(obj) as DeliveryNumberGenerator).ToArray();
            gens.AddRange(objs);
        }

        /// <summary>
        /// 生成下一个快递单号，普通的
        /// </summary>
        /// <param name="deliveryNumberAlgorithm"></param>
        /// <param name="current"></param>
        /// <returns></returns>
        public static WuliuNumber GenenrateNext(string deliveryNumberAlgorithm, string current)
        {
            DeliveryNumberGenerator gen = gens.FirstOrDefault(obj => obj.AcceptDeliveryCompany(deliveryNumberAlgorithm));
            if (gen == null)
            {
                throw new Exception("未能找到匹配的运单号生算法: " + deliveryNumberAlgorithm);
            }

            if (string.IsNullOrWhiteSpace(current))
            {
                throw new Exception("当前快递单号不能为空");
            }

            var deliveryNumber = gen.GenenrateNext(deliveryNumberAlgorithm, current);

            return new WuliuNumber { DeliveryNumber = deliveryNumber, WuliuId = "", DeliveryCompany = "", CreateTime = DateTime.Now };
        }

        /// <summary>
        /// 生成下一个快递单号，电子版本的
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static WuliuNumber GenenrateOnline(string deliveryNumberAlgorithm, Order order)
        {
            DeliveryNumberGenerator gen = gens.FirstOrDefault(obj => obj.AcceptDeliveryCompany(deliveryNumberAlgorithm));
            if (gen == null)
            {
                throw new Exception("未能找到匹配的运单号生算法: " + deliveryNumberAlgorithm);
            }

            //生成物流编号
            string wuliuId = "";
            if (order.OrderGoodss == null || order.OrderGoodss.Count < 1)
            {
                wuliuId = gen.GenenrateWuliuId(order.Id.ToString());
            }
            else
            {
                var ogs = order.OrderGoodss.Where(obj => (int)obj.State <= (int)OrderState.Shipped).ToArray();
                wuliuId = gen.GenenrateWuliuId(ogs.Select(obj => obj.OrderId.ToString()).Distinct().ToArray());
            }
            //检查是否有现成的
            var wuliuNumbers = ServiceContainer.GetService<WuliuNumberService>().GetByAll(wuliuId, order.DeliveryCompany, "", DateTime.MinValue, DateTime.MinValue, 0, 0).Datas;
            if (wuliuNumbers.Count > 1)
            {
                //检查信息是否一样
                if (wuliuNumbers[0].ReceiverAddress.Trim() != order.ReceiverAddress.Trim() ||
                    wuliuNumbers[0].ReceiverMobile.Trim() != order.ReceiverMobile.Trim() ||
                    wuliuNumbers[0].ReceiverName.Trim() != order.ReceiverName.Trim() ||
                    wuliuNumbers[0].ReceiverPhone.Trim() != order.ReceiverPhone.Trim())
                {
                    throw new Exception("订单已经绑定的信息与要打印的信息不一致");
                }
                return wuliuNumbers[0];
            }

            //请求在线的
            var deliveryNumber = gen.GenenrateOnline(order, wuliuId);
            var dbMinTime = ServiceContainer.GetService<WuliuNumberService>().GetDBMinTime();
            var wuliuNumber = new WuliuNumber { WuliuId = wuliuId, DeliveryNumber = deliveryNumber, CreateTime = DateTime.Now, DeliveryCompany = order.DeliveryCompany, ReceiverAddress = order.ReceiverAddress, ReceiverMobile = order.ReceiverMobile, ReceiverName = order.ReceiverName, ReceiverPhone = order.ReceiverPhone };
            ServiceContainer.GetService<WuliuNumberService>().Save(wuliuNumber);
            return wuliuNumber;
        }

        /// <summary>
        /// 取消快递单号
        /// </summary>
        /// <param name="ph"></param>
        public static void CancelOnline(WuliuNumber wuliuNumber)
        {
            DeliveryNumberGenerator gen = gens.FirstOrDefault(obj => obj.AcceptDeliveryCompany(wuliuNumber.DeliveryCompany));
            if (gen == null)
            {
                throw new Exception("未能找到匹配的运单号生算法: " + wuliuNumber.DeliveryCompany);
            }

            gen.CancelOnline(wuliuNumber);
        }
    }
}
